<template>
    <div ref="contain" class="echart_contain">
        <div v-if="showTitle" ref="title" class="echart_title">图表标题</div>
        <slot v-else name="title" ref="title"></slot>
        <slot name="content"></slot>
        <div :id="chartId" ref="chartDom"></div>
    </div>
</template>

<script setup>
// import * as echarts from 'echarts';
import { onMounted, ref, getCurrentInstance, nextTick, onBeforeUnmount } from 'vue';

const propsData = defineProps({
    chartId: {
        type: String,
        default: ''
    },
    showTitle: {
        type: Boolean,
        default: true
    }
});

const contain = ref(null);
const title = ref(null);
const chartDom = ref(null);
const initChart = async () => {
    const liHeight = contain.value?.clientHeight || 0;
    // console.log(`liHeight=>`, liHeight);
    let textHeight = title.value?.clientHeight || 0;
    chartDom.value.style.height = liHeight - textHeight + 'px';
    const chart = await globalProperties.$echarts.$renderChart(null, propsData.chartId, null);
    return chart;
};
const {
    appContext: {
        config: { globalProperties }
    }
} = getCurrentInstance();
const handleResize = () => {
    // TODO 防抖
    initChart();
};
const theResizeObserver = new ResizeObserver(handleResize);

onMounted(() => {
    nextTick(async () => {
        theResizeObserver.observe(contain.value);
        const res = await initChart();
        window.addEventListener('resize', () => {
            res.resize();
        });
    });
});
onBeforeUnmount(() => {
    theResizeObserver.unobserve(contain.value);
})
</script>

<style lang="scss" scoped>
.echart_contain {
    width: 100%;
    height: 100%;
    .echart_title {
        font-weight: bold;
        font-size: 20px;
    }
}
</style>
